package com.bwie.redkids;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.bwie.redkids.bean.CartBean;
import com.bwie.redkids.bean.DetailGoodsBean;
import com.bwie.redkids.bean.DetailGoodsBean.Product;
import com.bwie.redkids.bean.Favorites;
import com.bwie.redkids.utils.CartDBUtils;
import com.bwie.redkids.utils.FavoriteDBUtils;
import com.bwie.redkids.utils.GsonUtils;
import com.bwie.redkids.utils.PathUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.editorpage.ShareActivity;

public class DetailsActivity extends Activity implements OnClickListener {

	protected static final int SUCESS = 0;
	private ViewPager detail_viewPager;
	private LinearLayout ll_detail_points;
	private TextView goods_name;
	private TextView goods_smart;
	private TextView market_price;
	private TextView tv_detail_price;
	private Button bt_addCart;
	private Button bt_collect;
	private ArrayList<String> arrayList = new ArrayList<String>();
	private DetailGoodsBean detailGoodsBean;
	private int id;

	private FavoriteDBUtils favoriteDBUtils = new FavoriteDBUtils();
	private CartDBUtils cartDBUtils = new CartDBUtils();

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			if (msg.what == SUCESS) {
				detailGoodsBean = (DetailGoodsBean) msg.obj;
				arrayList.addAll(detailGoodsBean.getProduct().getPic());

				setData();
			}
		}
	};
	private ArrayList<ImageView> pointList;
	private Button detail_back;
	private ImageView tv_regist;
	private Product product;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_details);
		initView();
		initData();
		Intent intent = getIntent();
		id = intent.getIntExtra("id", 101);

		favoriteDBUtils.openSQLite(this);
		cartDBUtils.openSQLite(this);
	}

	private void initData() {
		new Thread() {
			private String path;

			public void run() {
				try {
					path = PathUtils.PATH + PathUtils.GOODS_DETAILS;
					String data = GsonUtils.getData(path);
					System.out.println("----------------data--------------"
							+ data);
					Gson gson = new Gson();
					DetailGoodsBean fromJson = gson.fromJson(data,
							DetailGoodsBean.class);
					System.out
							.println("---------------------------fromJson-----------------"
									+ fromJson.toString());
					handler.obtainMessage(SUCESS, fromJson).sendToTarget();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}

	private void initView() {
		detail_viewPager = (ViewPager) findViewById(R.id.detail_viewPager);
		ll_detail_points = (LinearLayout) findViewById(R.id.ll_detail_points);
		goods_name = (TextView) findViewById(R.id.goods_name);
		market_price = (TextView) findViewById(R.id.market_price);
		goods_smart = (TextView) findViewById(R.id.goods_smart);
		tv_detail_price = (TextView) findViewById(R.id.tv_detail_price);
		bt_addCart = (Button) findViewById(R.id.bt_addCart);
		bt_collect = (Button) findViewById(R.id.bt_collect);
		detail_back = (Button) findViewById(R.id.detail_back);
		tv_regist = (ImageView) findViewById(R.id.tv_regist);

		tv_regist.setOnClickListener(this);
		detail_back.setOnClickListener(this);
		bt_addCart.setOnClickListener(this);
		bt_collect.setOnClickListener(this);
	}

	private void setData() {
		product = detailGoodsBean.getProduct();
		goods_name.setText(detailGoodsBean.getProduct().getName());
		market_price.setText("市场价"
				+ detailGoodsBean.getProduct().getMarketprice());
		goods_smart.setText("用户评价" + detailGoodsBean.getProduct().getScore());
		tv_detail_price.setText("现价:"
				+ detailGoodsBean.getProduct().getLimitPrice()
				+ "       尽快抢购，过时不候！！！");

		detail_viewPager.setAdapter(new PagerAdapter() {

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return arrayList.size();
			}

			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object) {
				// super.destroyItem(container, position, object);
				container.removeView((View) object);
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				View view = View.inflate(DetailsActivity.this,
						R.layout.navigation_item, null);
				ImageView iv_navigation = (ImageView) view
						.findViewById(R.id.iv_navigation);
				BitmapUtils bitmapUtils = new BitmapUtils(DetailsActivity.this);
				bitmapUtils.display(iv_navigation, detailGoodsBean.getProduct()
						.getPic().get(position));
				container.addView(view);
				return view;
			}
		});
		initDots();
		detail_viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				for (int i = 0; i < arrayList.size(); i++) {
					if (i == position % arrayList.size()) {
						pointList.get(i).setImageResource(
								R.drawable.slide_adv_selected);
					} else {
						pointList.get(i).setImageResource(
								R.drawable.slide_adv_normal);
					}
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void initDots() {
		pointList = new ArrayList<ImageView>();
		pointList.clear();

		ll_detail_points.removeAllViews();
		for (int i = 0; i < arrayList.size(); i++) {
			ImageView imageView = new ImageView(this);
			// imageView.setPadding(10, 10, 10, 10);
			Drawable drawable = null;
			if (i == 0) {

				drawable = getResources().getDrawable(
						R.drawable.slide_adv_selected);

			} else {
				drawable = getResources().getDrawable(
						R.drawable.slide_adv_normal);
			}
			imageView.setImageDrawable(drawable);
			LayoutParams params = new LayoutParams(dip2px(this, 10), dip2px(
					this, 10));
			params.setMargins(dip2px(this, 5), 0, dip2px(this, 5), 0);
			ll_detail_points.addView(imageView, params);
			pointList.add(imageView);

		}
	}

	public int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	@Override
	public void onClick(View v) {
		UMShareListener umShareListener = null;
		switch (v.getId()) {
		case R.id.detail_back:
			DetailsActivity.this.finish();
			break;
		case R.id.tv_regist:
			final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[] {
					SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
					SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
					SHARE_MEDIA.DOUBAN };
			new ShareAction(this).setDisplayList(displaylist).withText("呵呵")
					.withTitle("title").withTargetUrl("www.baidu.com")
					.setListenerList(umShareListener).open();

			umShareListener = new UMShareListener() {
				@Override
				public void onResult(SHARE_MEDIA platform) {
					Toast.makeText(DetailsActivity.this, platform + " 分享成功啦",
							Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onError(SHARE_MEDIA platform, Throwable t) {
					Toast.makeText(DetailsActivity.this, platform + " 分享失败啦",
							Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onCancel(SHARE_MEDIA platform) {
					Toast.makeText(DetailsActivity.this, platform + " 分享取消了",
							Toast.LENGTH_SHORT).show();
				}
			};
			break;
		case R.id.bt_addCart:
			if (detailGoodsBean != null) {

				cartDBUtils.update(
						detailGoodsBean.getProduct().getId(),
						new CartBean(product.getId(), product.getName(), 1,
								product.getMarketprice(), product.getPic().get(
										0)));
				Toast.makeText(this, "已加入购物车", 0).show();
			}

			break;
		case R.id.bt_collect:

			if (detailGoodsBean != null) {
				if (bt_collect.isClickable()) {
					favoriteDBUtils.update(product.getId(), new Favorites(
							product.getId(), product.getName(), 1));
					Toast.makeText(this, "已收藏", 0).show();
				}
			}

			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		favoriteDBUtils.closeSQLite();
		cartDBUtils.closeSQLite();
	}
}
